﻿<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>请假申请管理</title>
    <link href="${pageContext.request.contextPath}/resources/bootstrap5/css/bootstrap.min.css" rel="stylesheet">
    <!-- 使用国内稳定的BootCDN Bootstrap Icons -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <!-- 备用CDN链接 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/resources/bootstrap5/all.min.css">
    <style>
        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f7fa;
            margin: 0;
            padding: 0;
        }
        .header {
            background: #2196f3;
            color: #fff;
            padding: 0 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 56px;
            box-shadow: 0 2px 8px rgba(33,150,243,0.08);
            position: fixed;
            width: 100%;
            top: 0;
            z-index: 1000;
        }
        .header-left {
            display: flex;
            align-items: center;
        }
        .header-logo {
            width: 36px;
            height: 36px;
            margin-right: 12px;
        }
        .header-title {
            font-size: 1.4rem;
            font-weight: bold;
            letter-spacing: 1px;
        }
        .header-nav {
            margin-left: 32px;
            font-size: 1rem;
        }
        .header-nav a {
            color: #fff;
            text-decoration: none;
            margin-right: 16px;
            opacity: 0.85;
        }
        .header-nav a.active, .header-nav a:hover {
            opacity: 1;
            font-weight: bold;
        }
        .sidebar {
            position: fixed;
            top: 56px;
            left: 0;
            bottom: 0;
            width: 220px;
            background: #fff;
            box-shadow: 2px 0 8px rgba(33,150,243,0.06);
            overflow-y: auto;
            z-index: 100;
            padding-top: 16px;
        }
        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .sidebar-menu > li {
            margin-bottom: 4px;
        }
        .sidebar-menu > li > a {
            display: flex;
            align-items: center;
            padding: 10px 24px;
            color: #333;
            text-decoration: none;
            border-radius: 8px 0 0 8px;
            transition: background 0.2s, color 0.2s;
            font-size: 1rem;
        }
        .sidebar-menu > li > a:hover, .sidebar-menu > li > a.active {
            background: #e3f2fd;
            color: #2196f3;
            font-weight: bold;
        }
        .sidebar-menu > li > a i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }
        .sidebar-submenu {
            list-style: none;
            padding-left: 40px;
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }
        .sidebar-menu > li.open .sidebar-submenu {
            max-height: 500px;
        }
        .sidebar-submenu > li > a {
            display: block;
            padding: 7px 0;
            color: #666;
            text-decoration: none;
            transition: color 0.2s;
            font-size: 0.98rem;
        }
        .sidebar-submenu > li > a:hover, .sidebar-submenu > li > a.active {
            color: #2196f3;
            font-weight: 500;
        }
        .content {
            margin-left: 240px;
            padding: 80px 32px 32px;
        }
        .card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(33,150,243,0.07);
            margin-bottom: 24px;
            border: none;
        }
        .card-body {
            padding: 24px 24px 16px 24px;
        }
        .search-bar {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 18px;
            flex-wrap: nowrap;
        }
        .search-bar select, .search-bar input {
            border-radius: 8px;
            border: 1px solid #e3e3e3;
            padding: 6px 14px;
            font-size: 1rem;
            flex: 1;
            min-width: 180px;
        }
        .search-bar .btn {
            border-radius: 8px;
            font-size: 1rem;
            padding: 6px 18px;
            font-weight: 500;
            box-shadow: none;
            flex-shrink: 0;
        }
        .btn-primary {
            background: #2196f3;
            border: none;
        }
        .btn-primary:hover {
            background: #1976d2;
        }
        .btn-warning {
            background: #ffb300;
            color: #fff;
            border: none;
        }
        .btn-warning:hover {
            background: #ff9800;
            color: #fff;
        }
        .btn-success {
            background: #43a047;
            border: none;
        }
        .btn-success:hover {
            background: #388e3c;
        }
        .btn-danger {
            background: #fff0f0;
            color: #e53935;
            border: 1px solid #ffcdd2;
        }
        .btn-danger:hover {
            background: #ffcdd2;
            color: #b71c1c;
        }
        .table {
            background: #fff;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(33,150,243,0.04);
        }
        .table thead th {
            background: #f5f7fa;
            color: #2196f3;
            font-weight: bold;
            text-align: center;
            border-bottom: 2px solid #e3e3e3;
        }
        .table tbody tr {
            transition: background 0.2s;
        }
        .table tbody tr:hover {
            background: #f1f8ff;
        }
        .table td, .table th {
            vertical-align: middle !important;
            text-align: center;
        }
        .pagination {
            justify-content: flex-start;
            margin-top: 12px;
        }
        .pagination .page-item .page-link {
            border-radius: 6px !important;
            margin: 0 2px;
            color: #2196f3;
            border: none;
            background: #fff;
            font-weight: 500;
            transition: background 0.2s, color 0.2s;
        }
        .pagination .page-item.active .page-link {
            background: #2196f3;
            color: #fff;
            font-weight: bold;
            border: none;
        }
        .pagination .page-link:hover {
            background: #e3f2fd;
            color: #2196f3;
        }
        .form-control {
            border-radius: 8px;
            border: 1px solid #e3e3e3;
        }
        .modal-content {
            border-radius: 12px;
        }

        /* 用户名下拉菜单样式 */
        .header-user {
            display: flex;
            align-items: center;
            position: relative;
        }
        .header-user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 8px;
            object-fit: cover;
            background: #fff;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .header-user-avatar:hover {
            transform: scale(1.1);
        }
        .header-user-name {
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        .user-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            min-width: 160px;
            z-index: 1001;
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s ease;
            margin-top: 8px;
        }
        .user-dropdown.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }
        .user-dropdown::before {
            content: '';
            position: absolute;
            top: -6px;
            right: 20px;
            width: 12px;
            height: 12px;
            background: #fff;
            transform: rotate(45deg);
            box-shadow: -2px -2px 4px rgba(0,0,0,0.1);
        }
        .user-dropdown-item {
            display: flex;
            align-items: center;
            padding: 12px 16px;
            color: #333;
            text-decoration: none;
            transition: background 0.2s;
            border-bottom: 1px solid #f0f0f0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        .user-dropdown-item:last-child {
            border-bottom: none;
        }
        .user-dropdown-item:hover {
            background: #f8f9fa;
            color: #2196f3;
        }
        .user-dropdown-item i {
            margin-right: 8px;
            width: 16px;
            text-align: center;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.85rem;
            font-weight: 500;
        }
        .status-pending {
            background: #fff3cd;
            color: #856404;
        }
        .status-approved {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }

        @media (max-width: 900px) {
            .content {
                margin-left: 0;
                padding: 80px 10px 10px;
            }
            .sidebar {
                width: 100%;
                position: static;
                box-shadow: none;
            }
            .search-bar {
                flex-wrap: wrap;
            }
            .search-bar select {
                min-width: 150px;
            }
        }
    </style>
</head>
<body>
<div class="header">
    <div class="header-left">
        <img src="${pageContext.request.contextPath}/resources/images/logo.png" alt="Logo" class="header-logo">
        <span class="header-title">教务管理系统</span>
        <div class="header-nav">
            <a href="${pageContext.request.contextPath}/admin/home">首页</a>
            <span style="opacity:0.5;">/</span>
            <a href="#" class="active">请假申请管理</a>
        </div>

    </div>

    <!-- 用户名下拉菜单 -->
    <div class="header-user" id="userDropdownContainer">
        <img src="${pageContext.request.contextPath}/resources/images/baimao.png" class="header-user-avatar" alt="用户名头像" id="userAvatar">
        <span class="header-user-name" id="userName">
                <c:choose>
                    <c:when test="${not empty sessionScope.loggedInUser and not empty sessionScope.loggedInUser.realName}">
                        ${sessionScope.loggedInUser.realName}
                    </c:when>
                    <c:when test="${not empty sessionScope.loggedInUser and not empty sessionScope.loggedInUser.username}">
                        ${sessionScope.loggedInUser.username}
                    </c:when>
                    <c:otherwise>
                        系统管理员
                    </c:otherwise>
                </c:choose>
            </span>
        <div class="user-dropdown" id="userDropdown">
            <a href="#" class="user-dropdown-item" id="profileBtn">
                <i class="bi bi-person-circle"></i>
                个人中心
            </a>
            <a href="${pageContext.request.contextPath}/user/logout" class="user-dropdown-item">
                <i class="bi bi-box-arrow-right"></i>
                退出系统
            </a>
        </div>
    </div>
</div>

<!-- 侧边栏 -->
<div class="sidebar">
    <ul class="sidebar-menu">
        <li>
            <a href="${pageContext.request.contextPath}/admin/home" class="active">
                <i class="bi bi-house-door"></i> 系统首页
            </a>
        </li>
        <li>
            <a href="#" class="has-submenu">
                <i class="bi bi-megaphone"></i> 信息公告
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/admin/notifications/academic">教学通知</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/notifications/exam">考试安排</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/notifications/classroom">教室安排</a></li>
            </ul>
        </li>
        <li>
            <a href="#" class="has-submenu">
                <i class="bi bi-building"></i> 行政管理
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/admin/college">学院信息</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/major">专业信息</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/class">班级信息</a></li>
            </ul>
        </li>
        <li>
            <a href="#" class="has-submenu">
                <i class="bi bi-book"></i> 教学管理
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/admin/course">课程信息</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/course-selection">选课管理</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/score">成绩管理</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/online">网上评教</a></li>
            </ul>
        </li>
        <li>
            <a href="#" class="has-submenu">
                <i class="bi bi-calendar3"></i> 教务管理
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/admin/leave">请假管理</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/homework">作业提交</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/attendance">考勤信息</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/online">网上评教</a></li>
            </ul>
        </li>
        <li>
            <a href="#" class="has-submenu">
                <i class="bi bi-person"></i> 用户管理
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/admin/admin">管理员信息</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/teacher">教师信息</a></li>
                <li><a href="${pageContext.request.contextPath}/admin/student">学生信息</a></li>
            </ul>
        </li>
        <li>
            <a href="${pageContext.request.contextPath}/user/logout">
                <i class="bi bi-box-arrow-right"></i> 退出系统
            </a>
        </li>
    </ul>
</div>

<!-- 主要内容区 -->
<div class="content">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">请假申请管理</h1>
    </div>

    <div class="card">
        <div class="card-body">
            <!-- 搜索栏 -->
            <form class="search-bar" method="get" action="${pageContext.request.contextPath}/admin/leave">
                <input type="text" class="form-control" name="studentName" value="${searchStudentName}" placeholder="请输入学生姓名">

                <select class="form-select" name="status">
                    <option value="">-- 选择审批状态 --</option>
                    <option value="0" ${searchStatus == 0 ? 'selected' : ''}>待审批</option>
                    <option value="1" ${searchStatus == 1 ? 'selected' : ''}>审批通过</option>
                    <option value="2" ${searchStatus == 2 ? 'selected' : ''}>审批不通过</option>
                </select>

                <button type="submit" class="btn btn-primary">查询</button>
                <a href="${pageContext.request.contextPath}/admin/leave" class="btn btn-warning">重置</a>
            </form>

            <!-- 操作按钮 -->
            <div class="mb-3" style="display:flex;gap:12px;">
                <button type="button" class="btn btn-danger" id="batchDeleteBtn">
                    批量删除
                </button>
            </div>

            <!-- 请假列表 -->
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th style="width: 5%;"><input type="checkbox" id="selectAllCheckbox"></th>
                        <th style="width: 8%;">序号</th>
                        <th style="width: 12%;">学生姓名</th>
                        <th style="width: 30%;">请假说明</th>
                        <th style="width: 20%;">请假时间</th>
                        <th style="width: 8%;">请假天数</th>
                        <th style="width: 12%;">审批状态</th>
                        <th style="width: 12%;">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <c:if test="${empty leaves}">
                        <tr>
                            <td colspan="8" class="text-center">暂无请假记录</td>
                        </tr>
                    </c:if>
                    <c:if test="${not empty leaves}">
                        <c:forEach var="leave" items="${leaves}" varStatus="status">
                            <tr>
                                <td><input type="checkbox" class="form-check-input item-checkbox" value="${leave.id}"></td>
                                <td>${status.count + (currentPage - 1) * pageSize}</td>
                                <td>
                                    <c:if test="${not empty leave.student and not empty leave.student.user and not empty leave.student.user.realName}">
                                        <c:out value="${leave.student.user.realName}"/>
                                    </c:if>
                                    <c:if test="${empty leave.student or empty leave.student.user or empty leave.student.user.realName}">
                                        未知学生
                                    </c:if>
                                </td>
                                <td>
                                    <c:choose>
                                        <c:when test="${not empty leave.reason}">
                                            <div title="${leave.reason}" style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                                <c:out value="${leave.reason}"/>
                                            </div>
                                        </c:when>
                                        <c:otherwise>
                                            <span class="text-muted">暂无说明</span>
                                        </c:otherwise>
                                    </c:choose>
                                </td>
                                <td>
                                    <c:choose>
                                        <c:when test="${not empty leave.startTime and not empty leave.endTime}">
                                            <c:out value="${leave.startTime}"/> 至 <c:out value="${leave.endTime}"/>
                                        </c:when>
                                        <c:otherwise>
                                            <span class="text-muted">未设置时间</span>
                                        </c:otherwise>
                                    </c:choose>
                                </td>
                                <td>
                                    <c:choose>
                                        <c:when test="${leave.leaveDays > 0}">
                                            ${leave.leaveDays}
                                        </c:when>
                                        <c:otherwise>
                                            <span class="text-muted">-</span>
                                        </c:otherwise>
                                    </c:choose>
                                </td>
                                <td>
                                    <c:choose>
                                        <c:when test="${leave.status == 0}">
                                            <span class="status-badge status-pending">待审批</span>
                                        </c:when>
                                        <c:when test="${leave.status == 1}">
                                            <span class="status-badge status-approved">审批通过</span>
                                        </c:when>
                                        <c:when test="${leave.status == 2}">
                                            <span class="status-badge status-rejected">审批不通过</span>
                                        </c:when>
                                        <c:otherwise>
                                            <span class="text-muted">未知状态</span>
                                        </c:otherwise>
                                    </c:choose>
                                </td>
                                <td>
                                    <c:if test="${leave.status == 0}">
                                        <button class="btn btn-success btn-sm approve-btn" data-id="${leave.id}" data-action="1" title="审批">
                                            审批
                                        </button>
                                    </c:if>
                                    <button class="btn btn-danger btn-sm delete-btn" data-id="${leave.id}" title="删除">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        </c:forEach>
                    </c:if>
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center">
                    <c:if test="${not empty currentPage and currentPage > 1}">
                        <li class="page-item">
                            <a class="page-link" href="?page=${currentPage - 1}&studentName=${searchStudentName}&status=${searchStatus}" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                    </c:if>

                    <c:if test="${not empty totalPages}">
                        <c:forEach begin="1" end="${totalPages}" var="i">
                            <li class="page-item ${currentPage == i ? 'active' : ''}">
                                <a class="page-link" href="?page=${i}&studentName=${searchStudentName}&status=${searchStatus}">${i}</a>
                            </li>
                        </c:forEach>
                    </c:if>

                    <c:if test="${not empty currentPage and not empty totalPages and currentPage < totalPages}">
                        <li class="page-item">
                            <a class="page-link" href="?page=${currentPage + 1}&studentName=${searchStudentName}&status=${searchStatus}" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    </c:if>
                </ul>
                <div class="text-left mt-2" style="font-size:0.98rem;color:#888;">
                    共 ${totalRecords} 条
                </div>
            </nav>
        </div>
    </div>
</div>

<!-- 审批模态框 -->
<div class="modal fade" id="approveModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-check-circle me-2"></i>审批请假申请
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">审批结果</label>
                    <div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="approveStatus" id="approve" value="1" checked>
                            <label class="form-check-label" for="approve">
                                审批通过
                            </label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="approveStatus" id="reject" value="2">
                            <label class="form-check-label" for="reject">
                                审批不通过
                            </label>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmApprove">确认审批</button>
            </div>
        </div>
    </div>
</div>

<!-- 个人中心模态框 -->
<div class="modal fade" id="profileModal" tabindex="-1" aria-labelledby="profileModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="profileModalLabel">个人中心</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <ul class="nav nav-tabs" id="profileTabs" role="tablist">
                    <li class="nav-item">
                        <button class="nav-link active" id="profile-info-tab" data-bs-toggle="tab" data-bs-target="#profile-info" type="button" role="tab" aria-controls="profile-info" aria-selected="true">
                            <i class="bi bi-person"></i> 个人信息
                        </button>
                    </li>
                    <li class="nav-item">
                        <button class="nav-link" id="change-password-tab" data-bs-toggle="tab" data-bs-target="#change-password" type="button" role="tab" aria-controls="change-password" aria-selected="false">
                            <i class="bi bi-key"></i> 修改密码
                        </button>
                    </li>
                </ul>
                <div class="tab-content" id="profileTabContent">
                    <div class="tab-pane fade show active" id="profile-info" role="tabpanel" aria-labelledby="profile-info-tab">
                        <form id="profileForm" class="mt-3">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="profileUsername" class="form-label">用户名</label>
                                        <input type="text" class="form-control" id="profileUsername" readonly>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="profileRole" class="form-label">角色</label>
                                        <input type="text" class="form-control" id="profileRole" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="profileRealName" class="form-label">真实姓名</label>
                                <input type="text" class="form-control" id="profileRealName" required>
                            </div>
                            <div class="d-grid gap-2">
                                <button type="button" class="btn btn-primary" id="updateProfileBtn">
                                    <i class="bi bi-check-circle"></i> 更新信息
                                </button>
                            </div>
                        </form>
                    </div>
                    <div class="tab-pane fade" id="change-password" role="tabpanel" aria-labelledby="change-password-tab">
                        <form id="passwordForm" class="mt-3">
                            <div class="mb-3">
                                <label for="oldPassword" class="form-label">原密码</label>
                                <input type="password" class="form-control" id="oldPassword" required>
                            </div>
                            <div class="mb-3">
                                <label for="newPassword" class="form-label">新密码</label>
                                <input type="password" class="form-control" id="newPassword" required minlength="6">
                                <div class="form-text">密码长度至少6位</div>
                            </div>
                            <div class="mb-3">
                                <label for="confirmPassword" class="form-label">确认新密码</label>
                                <input type="password" class="form-control" id="confirmPassword" required>
                            </div>
                            <div class="d-grid gap-2">
                                <button type="button" class="btn btn-warning" id="changePasswordBtn">
                                    <i class="bi bi-key"></i> 修改密码
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="${pageContext.request.contextPath}/resources/bootstrap5/jquery-3.6.0.min.js"></script>
<script src="${pageContext.request.contextPath}/resources/bootstrap5/js/bootstrap.bundle.min.js"></script>

<script>
    $(document).ready(function() {
        // 用户名下拉菜单功能
        let userDropdownTimeout;

        $('#userDropdownContainer').hover(
            function() {
                clearTimeout(userDropdownTimeout);
                $('#userDropdown').addClass('show');
            },
            function() {
                userDropdownTimeout = setTimeout(function() {
                    $('#userDropdown').removeClass('show');
                }, 300);
            }
        );

        // 点击头像或用户名也可以显示下拉菜单
        $('#userAvatar, #userName').click(function(e) {
            e.preventDefault();
            $('#userDropdown').toggleClass('show');
        });

        // 点击其他地方隐藏下拉菜单
        $(document).click(function(e) {
            if (!$(e.target).closest('#userDropdownContainer').length) {
                $('#userDropdown').removeClass('show');
            }
        });

        // 个人中心功能
        $('#profileBtn').click(function(e) {
            e.preventDefault();
            $('#userDropdown').removeClass('show');
            loadUserProfile();
            $('#profileModal').modal('show');
        });

        // 加载用户个人信息
        function loadUserProfile() {
            $.ajax({
                url: '${pageContext.request.contextPath}/user/profile',
                type: 'GET',
                success: function(response) {
                    if (response.success) {
                        const user = response.user;
                        $('#profileUsername').val(user.username);
                        $('#profileRealName').val(user.realName || '');

                        // 设置角色显示
                        let roleText = '';
                        switch(user.role) {
                            case 1: roleText = '管理员'; break;
                            case 2: roleText = '教师'; break;
                            case 3: roleText = '学生'; break;
                            default: roleText = '未知'; break;
                        }
                        $('#profileRole').val(roleText);
                    } else {
                        alert('获取用户个人信息失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('获取用户个人信息失败，请重试');
                }
            });
        }

        // 更新个人信息
        $('#updateProfileBtn').click(function() {
            const realName = $('#profileRealName').val().trim();
            if (!realName) {
                alert('请输入真实姓名');
                return;
            }

            $.ajax({
                url: '${pageContext.request.contextPath}/user/updateProfile',
                type: 'POST',
                data: {
                    realName: realName
                },
                success: function(response) {
                    if (response.success) {
                        alert('个人信息更新成功');
                        // 更新页面显示的用户名
                        $('#userName').text(realName);
                        $('#profileModal').modal('hide');
                        // 刷新页面以更新所有显示的用户名
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    } else {
                        alert('更新失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('更新失败，请重试');
                }
            });
        });

        // 修改密码
        $('#changePasswordBtn').click(function() {
            const oldPassword = $('#oldPassword').val();
            const newPassword = $('#newPassword').val();
            const confirmPassword = $('#confirmPassword').val();

            if (!oldPassword || !newPassword || !confirmPassword) {
                alert('请填写完整的密码信息');
                return;
            }

            if (newPassword.length < 6) {
                alert('新密码长度不能少于6位');
                return;
            }

            if (newPassword !== confirmPassword) {
                alert('新密码和确认密码不一致');
                return;
            }

            $.ajax({
                url: '${pageContext.request.contextPath}/user/changePassword',
                type: 'POST',
                data: {
                    oldPassword: oldPassword,
                    newPassword: newPassword,
                    confirmPassword: confirmPassword
                },
                success: function(response) {
                    if (response.success) {
                        alert('密码修改成功');
                        $('#passwordForm')[0].reset();
                        $('#profileModal').modal('hide');
                    } else {
                        alert('修改失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('修改失败，请重试');
                }
            });
        });

        // 模态框关闭时重置表单
        $('#profileModal').on('hidden.bs.modal', function() {
            $('#profileForm')[0].reset();
            $('#passwordForm')[0].reset();
            // 切换回个人信息标签
            $('#profile-info-tab').tab('show');
        });
    });
</script>

<script>
    $(document).ready(function() {
        let currentLeaveId = null;

        // 用户名下拉菜单
        $('#userDropdownContainer').click(function(e) {
            e.stopPropagation();
            $('#userDropdown').toggleClass('show');
        });

        $(document).click(function() {
            $('#userDropdown').removeClass('show');
        });

        // 侧边栏子菜单
        $('.has-submenu').click(function(e) {
            e.preventDefault();
            $(this).parent().toggleClass('open');
        });

        // 全选/取消全选
        $("#selectAllCheckbox").change(function() {
            $(".item-checkbox").prop("checked", this.checked);
            updateBatchDeleteButton();
        });

        // 单项选择
        $(".item-checkbox").change(function() {
            const totalCheckboxes = $(".item-checkbox").length;
            const checkedCheckboxes = $(".item-checkbox:checked").length;
            $("#selectAllCheckbox").prop("checked", totalCheckboxes === checkedCheckboxes);
            updateBatchDeleteButton();
        });

        // 更新批量删除按钮状态
        function updateBatchDeleteButton() {
            const checkedCount = $(".item-checkbox:checked").length;
            $("#batchDeleteBtn").prop("disabled", checkedCount === 0);
        }

        // 批量删除
        $("#batchDeleteBtn").click(function() {
            const selectedIds = [];
            $(".item-checkbox:checked").each(function() {
                selectedIds.push($(this).val());
            });

            if (selectedIds.length === 0) {
                alert("请选择要删除的请假记录");
                return;
            }

            if (confirm("确定要删除选中的 " + selectedIds.length + " 条请假记录吗？此操作不可恢复！")) {
                window.location.href = "${pageContext.request.contextPath}/admin/leave/batchDelete?ids=" + selectedIds.join(",");
            }
        });

        // 审批按钮
        $(".approve-btn").click(function() {
            currentLeaveId = $(this).data("id");
            $("#approveModal").modal("show");
        });

        // 确认审批
        $("#confirmApprove").click(function() {
            if (currentLeaveId == null) {
                return;
            }

            const status = $("input[name='approveStatus']:checked").val();

            $.post("${pageContext.request.contextPath}/admin/leave/approve/" + currentLeaveId, {
                status: status
            }, function(data) {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert("审批失败：" + data.message);
                }
            }).fail(function() {
                alert("审批失败，请重试");
            });

            $("#approveModal").modal("hide");
        });

        // 删除按钮
        $(".delete-btn").click(function() {
            const id = $(this).data("id");
            if (confirm("确定要删除这条请假记录吗？此操作不可恢复！")) {
                window.location.href = "${pageContext.request.contextPath}/admin/leave/delete/" + id;
            }
        });

        // 个人中心按钮
        $("#profileBtn").click(function(e) {
            e.preventDefault();
            // 获取用户信息
            $.ajax({
                url: "${pageContext.request.contextPath}/user/profile",
                method: "GET",
                dataType: "json",
                success: function(data) {
                    $("#username").val(data.username);
                    $("#realName").val(data.realName);
                    $("#email").val(data.email);
                    $("#phone").val(data.phone);
                    $("#role").val(data.roleName);
                    $("#department").val(data.departmentName);
                    $("#profileModal").modal("show");
                },
                error: function() {
                    alert("获取用户信息失败");
                }
            });
        });

        // 保存个人信息
        $("#profileForm").submit(function(e) {
            e.preventDefault();

            const formData = {
                realName: $("#realName").val(),
                email: $("#email").val(),
                phone: $("#phone").val()
            };

            $.ajax({
                url: "${pageContext.request.contextPath}/user/updateProfile",
                method: "POST",
                data: JSON.stringify(formData),
                contentType: "application/json",
                dataType: "json",
                success: function(data) {
                    if (data.success) {
                        alert("个人信息更新成功");
                        $("#profileModal").modal("hide");
                        // 更新页面上的用户名显示
                        $("#userName").text(data.realName);
                    } else {
                        alert("更新失败：" + data.message);
                    }
                },
                error: function() {
                    alert("更新失败，请重试");
                }
            });
        });

        // 初始化批量删除按钮状态
        updateBatchDeleteButton();
    });
</script>
</body>
</html>
